package com.wxy.dao;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Date;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import com.wxy.mapper.UserMapper;
import com.wxy.pojo.User;



public class DaoUser {

	private static SqlSessionFactory sqlSessionFactory;

	// 创建会话工厂
	public static void getFactory() {
		// 加载核心配置文件
		String resource = "sqlMapConfig.xml";
		InputStream is = DaoUser.class.getClassLoader().getResourceAsStream(resource);
		sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);

	}

	// 查询操作
	public static User select(Integer id) {

		getFactory();
		// 创建SqlSession
		SqlSession sqlSession = sqlSessionFactory.openSession();
		// 加载接口
		UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
		User user = userMapper.selectUserById(id);
		//System.out.println(user);
		return user;

	}

	// 插入操作
	public static void insert(User user) {

		getFactory();
		// 创建SqlSession
		SqlSession sqlSession = sqlSessionFactory.openSession();
		try {
			// 加载接口
			UserMapper userOperation = sqlSession.getMapper(UserMapper.class);
			userOperation.insertUser(user);
			sqlSession.commit();

		} finally {
			sqlSession.close();
			System.out.println("session.close();");
		}
	}

	// 更新操作
	public static void update(User user) {
		getFactory();
		// 创建SqlSession
		SqlSession sqlSession = sqlSessionFactory.openSession();
		try {
			// 加载接口
			UserMapper userOperation = sqlSession.getMapper(UserMapper.class);
			userOperation.updateUser(user);
			sqlSession.commit();

		} finally {
			sqlSession.close();
			System.out.println("session.close();");
		}
	}

	// 删除操作
	public static void delete(Integer id) {
		getFactory();
		// 创建SqlSession
		SqlSession sqlSession = sqlSessionFactory.openSession();
		try {
			// 加载接口
			UserMapper userOperation = sqlSession.getMapper(UserMapper.class);
			userOperation.deleteUserById(id);
			sqlSession.commit();

		} finally {
			sqlSession.close();
			System.out.println("session.close();");
		}
	}

	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		//mybatis连接测试
		User user = new User();
		user.setUsername("zzz");
		user.setId(2);
		user.setAddress("vvvvvvvv");
		user.setBirthday(new Date(0));
		user.setSex("男");

		User userinfo=select(2);
		System.out.println(userinfo);
		// insert(user);
		// update(user);
		//delete(1);
	}

}
